package 
{
import com.bit101.components.PushButton;

import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.MouseEvent;
import flash.geom.Point;
import flash.utils.Dictionary;
public class Main extends Sprite
{
	private var _personPoint:Point;
	private var _grid:GridDesign;
	//当前方向 0, 1, 2, 3 分别表示右, 上, 左, 下
	private var _direction:uint = 0;
	
	public function Main()
	{
		stage.align = StageAlign.TOP_LEFT;
		stage.scaleMode = StageScaleMode.NO_SCALE;
		
		this._personPoint = new Point(1, 1);
		
		_grid = new GridDesign();
		addChild(_grid);
		
		var btn:PushButton  = new PushButton(this, 300, 200, "click");
		btn.addEventListener(MouseEvent.CLICK, getOut);
	}

	/**
	 * 开始逃出
	 */
	private function getOut(event : MouseEvent) : void
	{
		while (!this.ifOutSide())
		{
			this.turnRight();
			while (this.ifFaceWall())
			{
				this.turnLeft();
			}
			
			this.moveForward();
		}
	}
	
	/**
	 * 向前(根据direction)移动一格
	 */
	private function moveForward():void
	{
		this._personPoint = getForwardPoint();
		trace(this._personPoint);
	}
	
	private function getForwardPoint():Point
	{
		var result:Point = new Point(this._personPoint.x, this._personPoint.y);
		switch(this._direction){
			case 0:
				result.x += 1;
				break;
				
			case 1:
				result.y -= 1;
				break;
			
			case 2:
				result.x -= 1;
				break;
				
			case 3:
				result.y += 1;
				break;
		}
		return result;
	}
	
	/**
	 * 左转
	 */
	private function turnLeft():void
	{
		if (this._direction == 3)
		{
			this._direction = 0;
		}
		else 
		{
			this._direction += 1;
		}
		
		trace("currentDirection:" + this._direction);
	}
	
	/**
	 * 右转
	 */
	private function turnRight():void
	{
		if (this._direction == 0)
		{
			this._direction = 3;
		}
		else
		{
			this._direction -= 1;
		}
		trace("currentDirection:" + this._direction);
	}
	
	/**
	 * 人物是否面对墙
	 */
	private function ifFaceWall():Boolean
	{
		var mapInfo:Dictionary = this._grid.getMapInfo();
		var forwardPoint:Point = getForwardPoint();
		
		var result:Boolean = mapInfo[forwardPoint.x + "-" + forwardPoint.y] == 1;
		var des:String = result? "墙":"非墙";
		trace("direction是" + _direction + ", 面对" + forwardPoint.x + ":" + forwardPoint.y + des);
		return result;
	}
	
	/**
	 * 判断是否逃出
	 */
	private function ifOutSide():Boolean
	{
		return this._personPoint.x >= this._grid.gridHCount || this._personPoint.y >= this._grid.gridVCount
				|| this._personPoint.x <= 0 || this._personPoint.y <= 0;
	}
}
}
